#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QThread>
#include <QImage>
#include <QPainter>
#include "InfoNES.h"
#include "QKeyEvent"
#include <QAudioOutput>
#include <QByteArray>
#include <QIODevice>
#include <QTimer>
#include <QScopedPointer>

#include <QtDebug>

#define IMG_WIDTH   NES_DISP_WIDTH
#define IMG_HEIGHT  NES_DISP_HEIGHT

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

extern int LoadFrame_flag;

void infoNes_clean();
void InfoNES_loop();
int start_application(QString fn);

//----------------------------------------------------------------------------
class WorkerThread : public QThread
{
    Q_OBJECT
public:
    WorkerThread(){
        quit = 0;
    }
    ~WorkerThread()
    {
        qDebug()<<"WorkerThread delete";
    }
public:
    void set_quit(quint8 s=1)
    {
        quit = s;
    }
    void set_file_name(QString fn);
private:
    void run() override;
signals:
    void update_img_signal(int s);

private:

    quint8 quit;
    QString nes_file_name;
};

//----------------------------------------------------------------------------
class Generator : public QIODevice
{
    Q_OBJECT

public:
    Generator(const QAudioFormat &format, qint64 durationUs, int sampleRate);
    ~Generator();
    void start();
    void stop();

    qint64 readData(char *data, qint64 maxlen) override;
    qint64 writeData(const char *data, qint64 len) override;
    qint64 bytesAvailable() const override;

private:
//    void generateData(const QAudioFormat &format, qint64 durationUs, int sampleRate);

private:
    qint64 m_pos = 0;
    QByteArray m_buffer;
};

//----------------------------------------------------------------------------
class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
private:
    void startWorkInAThread();
protected:
    void paintEvent(QPaintEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void keyReleaseEvent(QKeyEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
private:
    void update_img_slot(int s);
    void initAudio();
private:
    Ui::Widget *ui;
    WorkerThread *workerThread;
    QImage *m_img;
    quint64 update_count=0;
    QScopedPointer<QAudioOutput> m_audioOutput;
    QScopedPointer<Generator> m_generator;
};
#endif // WIDGET_H
